<template>
    <van-nav-bar title="编辑收货地址" left-arrow @click-left="onBack" />

    <van-address-edit :area-list="areaList" show-delete show-set-default :address-info="addressInfo"
        :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete" />
</template>
<script setup>
import { areaList } from '@vant/area-data';
import { reactive, onMounted } from 'vue'
import apiList from '@/api'
import resJudge from '@/hooks/res';
import { useRouter, useRoute } from 'vue-router';
import { showNotify, showConfirmDialog } from 'vant'

const router = useRouter()
const route = useRoute()


let addressInfo = reactive({})

onMounted(() => {
    getAddressData(route.query)
})

//导航条返回
const onBack = () => history.back()

//获取地址查询的信息
async function getAddressData(data) {
    let res = await apiList.AddressEditQuery(data)
    if (res.code === 0) {
        showNotify({
            type: 'warning',
            duration: 1500,
            message: res.msg,
        })
    } else {
        addressInfo.name = res.data.consignee
        addressInfo.tel = res.data.mobile
        // addressInfo.city = res.data.region_text
        addressInfo.areaCode = res.data.district
        addressInfo.addressDetail = res.data.address
        addressInfo.isDefault = parseInt(res.data.status) ? true : false
    }
}

//保存
async function onSave(info) {
    let data = {
        id: route.query.id,
        busid: route.query.busid,
        consignee: info.name,
        mobile: info.tel,
        status: info.isDefault === true ? 1 : 0,
        address: info.addressDetail,
        code: info.areaCode
    }
    let res = await apiList.AddressEditSave(data)
    if (resJudge(res)) {
        if (route.query.action == 'order' || route.query.action == 'productInfo') {
            router.back()
        } else {
            router.push('/business/address/index')
        }
    }
}

//删除
function onDelete() {
    showConfirmDialog({
        // title: '注销',
        message: '确定删除吗？',
    })
        .then(async () => {
            // on confirm
            let res = await apiList.AddressEditDelete(route.query)
            if (resJudge(res)) {
                if (route.query.action == 'order' || route.query.action == 'productInfo') {
                    router.back()
                } else {
                    router.push('/business/address/index')
                }
            }
        })
        .catch(() => {
            // on cancel
        });
}
</script>
